package pers.xiqingbo.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @PackageName: ${PACKAGE_NAME}
 * @ClassName: ${NAME}
 * @Description: 后台管理模块过滤filter
 * @Author: Schieber
 * @Date: 2021/3/4 上午 4:53
 */
public class ManagerFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        // 将ServletRequest转换为HttpServletRequest
        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        // Filter共享同一个request域和同一个线程 HttpServletRequest获取Session中
        Object user = httpServletRequest.getSession().getAttribute("user");
        // 如果用户未登录则跳转至登录页面
        if (user == null) {
            httpServletRequest.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        } else {
            // 否则执行过滤器doFilter放行
            chain.doFilter(req, resp);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
